import React, { useState, useEffect } from 'react';
import { cline, uJob, ErrView, Wait, obj_str, BaseDlg, NuiBt } from 'sui';
import { g_db } from 'db/state';
import { loc } from 'local';
import { Scan, Pcode} from './ctl';

const DlgBind = ({ open, setOpen }) => {
    const [fin, setFin] = useState("scan");
    const [err, setErr] = useState("");
    const [wait, setWait] = useState(false);

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");

        g_db.stop_scan();
    }, [open]);

    const hbind = (msn) => {
        if (!msn) {
            return;
        }

        setWait(true);

        uJob(null, "pick/free",
            {
                line: cline(),
                k: msn,
            },
            r => {
                setWait(false);

                if (r) {
                    setErr(`料箱和下面工单有绑定关系: 工单 ${obj_str(r, "task")}, 圈号 ${obj_str(r, "sn")}`);;
                    return;
                }

                setOpen(false);
                g_db.start_scan();
            },
            e => {
                setWait(false);
                setErr("解绑失败");;
            });
    };

    const getView = () => {
        if (fin === "scan") {
            return <Scan hcmd={hbind} open={open} setOpen={setOpen}/>;
        }

        return <Pcode hcmd={hbind} open={open} setOpen={setOpen}/>;
    };

    return (
        <BaseDlg open={open} title="解绑料箱">
            <div className="flex flex-col">
                <div className="flex flex-row ml-4">
                    <NuiBt color={fin === "scan" ? "green": "blue"} hcmd={() => setFin("scan")}>{loc("base_62")}</NuiBt>
                    <NuiBt className="ml-4" color={fin === "scan" ? "blue": "green"} hcmd={() => setFin("pass")}>{loc("base_59")}</NuiBt>
                </div>
                <ErrView err={err}/>
                {getView()}
                <Wait wait={wait}/>
            </div>
        </BaseDlg>
    );
};

export {DlgBind};
